//
//  SEGThirdConfigManager.m
//  Commom
//
//  Created by 梁学彰 on 2020/8/31.
//

#import "SEGThirdConfigManager.h"

#import <CommonMediator/SEGUhomeMediator.h>
#import <Commom/SEGCommonConfig.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "SEGPlatformHeader.h"
#import "SEGMediatorUhomeHeader.h"
#import "SEGMediatorHeader.h"
#import <SVProgressHUD.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <AlipaySDK/AlipaySDK.h>
@interface SEGThirdConfigManager ()

@end

@implementation SEGThirdConfigManager
+ (instancetype)sharedInstance
{
    static SEGThirdConfigManager *mediator;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mediator = [[SEGThirdConfigManager alloc] init];
    });
    return mediator;
}

- (void)segInitThirdSDK {
    
    BOOL isSign = [[SEGUhomeMediator sharedInstance] seg_initUMSPPPayWithParams:nil];
    if (!isSign) {
        NSLog(@"UMSPPPayUnifyPayPlugin  registerApp  失败");
//#ifdef DEBUG
//        NSAssert(isSign, @"注册不成功，请检查kWeChatAppId 和 kUniversalLink");
//#endif
    }
    TencentOAuth *tencentOAuth = [[TencentOAuth alloc] initWithAppId:kQQAppId andDelegate:nil];
    if (!tencentOAuth) {
        NSLog(@"TencentOAuth  registerApp  失败");
    }

    //开启四格埋点统计
    [[SEGUhomeMediator sharedInstance] seg_startAnalytics:@{}]; //开启四格埋点统计
    [[SEGUhomeMediator sharedInstance] seg_startMobAnalytics:@{@"appKey":kUMengAnalyticsAppKey}];
    [[SEGUhomeMediator sharedInstance] seg_initBMKLocationKit:@{@"appKey":kBaiduMapAppKey}]; //初始化百度地图
        
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    [SVProgressHUD setBackgroundLayerColor:[[UIColor whiteColor] colorWithAlphaComponent:0.2]];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
}


//统一处理openURL
- (BOOL)dealWithOpenUrl:(NSURL*)url
{
    //url打开应用(返回的全部是小写)
    if ([url.scheme isEqualToString:kWeChatAppId])//微信
    {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            if ([resultDic.allKeys containsObject:@"resultStatus"]) {
                NSString *code = resultDic[@"resultStatus"];
                if (code.integerValue == 9000) {
                    NSNotification* notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"success"];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                }else {
                    [SEGAlertView showTmepMessageWithMessage:resultDic[@"memo"]];
                }
            }
        }];
        return YES;
    }
    
    if ([[url absoluteString] hasSuffix:@"ICBCB2CPAY"]) {
        [[SEGUhomeMediator sharedInstance] seg_initICBCPayBackWithParams:@{@"url":url}];
        return YES;
    }
    
    
    if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",kQQAppId]]){//QQ
        //处理QQ分享结果
        // tencent1103195997://response_from_qq?source=qq&source_scheme=mqqapi&error=0&version=1
        // tencent1103195997://response_from_qq?error_description=dGhlIHVzZXIgZ2l2ZSB1cCB0aGUgY3VycmVudCBvcGVyYXRpb24=&source=qq&source_scheme=mqqapi&error=-4&version=1
        //提取参数error进行判断
        NSString *urlStr = url.resourceSpecifier;
        NSRange range = [urlStr rangeOfString:@"?"];
        if (range.location != NSNotFound) {
            NSString *parametersString = [urlStr substringFromIndex:range.location + 1];
            NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            for (NSString *keyValuePair in urlComponents) {
                NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
                NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
                NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
                if (key == nil || value == nil) {
                    continue;
                }
                [params setValue:value forKey:key];
            }
            if ([params objectForKey:@"error"] && [[params objectForKey:@"error"] isEqualToString:@"0"]) {//分享成功
                [self shareSuccess];
            }
        }
        return [QQApiInterface handleOpenURL:url delegate:nil];
    }
    
    if([url.scheme isEqualToString:kOpenAppScheme]) {//分享的网页打开应用
        //提取参数进行页面跳转
        NSString* string = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        if ([string hasPrefix:@"params="]) {
            string = [string substringFromIndex:@"params=".length];
        }
        //字符串转字典
        NSDictionary* dict = [SEGUtils dictionaryWithJsonString:string];
        NSMutableDictionary *inputParams = [NSMutableDictionary dictionary];
        
        if ([url.resourceSpecifier rangeOfString:@"bonuse-sys.detail"].location != NSNotFound) {//积分商城详情
            
            NSString *objId = ValueToString(dict[@"id"]);
            if (objId && objId.length > 0) {
                [inputParams setObject:objId forKey:@"id"];
                [inputParams setObject:@(SEGOpenFromJsType_WebView) forKey:@"type"];
                [inputParams setObject:kIntegarlCommodityDetail(objId) forKey:@"linkURL"];
                
            }
            
        }else if ([url.resourceSpecifier rangeOfString:@"segi.activity-manage.list"].location != NSNotFound) {//活动管理列表界面
            
            [inputParams setObject:@(SEGOpenFromJsType_ActivityList) forKey:@"type"];
            
        }else if ([url.resourceSpecifier rangeOfString:@"segi.activity-manage.detail"].location != NSNotFound) {//活动管理详情页
            
            NSString *objId = ValueToString(dict[@"objId"]);
            if (objId && objId.length > 0) {
                [inputParams setObject:@(SEGOpenFromJsType_ActivityDetail) forKey:@"type"];
                [inputParams setObject:objId forKey:@"id"];
            }
            
        }else if ([url.resourceSpecifier rangeOfString:@"segi.pgc.detail"].location != NSNotFound) {//PGC分享界面
            NSString *objId = ValueToString(dict[@"objId"]);
            
            if (objId && objId.length > 0) {
                [inputParams setObject:@(SEGOpenFromJsType_PGC) forKey:@"type"];
                [inputParams setObject:objId forKey:@"id"];
            }
            
        }else if ([url.resourceSpecifier rangeOfString:@"segi.ugc.detail"].location != NSNotFound) {//UGC分享界面
            
            NSString *objId = ValueToString(dict[@"objId"]);
            NSString *objType = ValueToString(dict[@"objType"]);
            NSString *operationType = ValueToString(dict[@"operationType"]);
            
            if (objId && objId.length > 0 && objType && objType.length > 0 && operationType && operationType.length > 0) {
                
                [inputParams setObject:@(SEGOpenFromJsType_UGC) forKey:@"type"];
                [inputParams setObject:objType forKey:@"objType"];
                [inputParams setObject:operationType forKey:@"operationType"];
                [inputParams setObject:objId forKey:@"objId"];
                
            }
        }else if ([url.resourceSpecifier rangeOfString:@"segi.topic.detail"].location != NSNotFound) {//话题详情界面
            NSString *objId = ValueToString(dict[@"objId"]);
            if (objId && objId.length > 0) {
                
                [inputParams setObject:objId forKey:@"id"];
                [inputParams setObject:@(SEGOpenFromJsType_TopicDetail) forKey:@"type"];
                
            }
        }else if ([url.resourceSpecifier rangeOfString:@"segi.notice.detail"].location != NSNotFound) {//物业通知详情界面
            NSString *objId = ValueToString(dict[@"objId"]);
            NSString *pictorialTitle = ValueToString(dict[@"title"]);
            if (objId && objId.length > 0 && pictorialTitle && pictorialTitle.length > 0) {
                
                [inputParams setObject:objId forKey:@"id"];
                [inputParams setObject:@(SEGOpenFromJsType_NoticeDetail) forKey:@"type"];
                [inputParams setObject:pictorialTitle forKey:@"pictorialTitle"];
                
            }
        }
        
        [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithScheme:inputParams];
        if ([[url absoluteString] hasPrefix:kOpenAppScheme])
        {
            return [[SEGUhomeMediator sharedInstance] seg_UMSPPPaycloudPayHandleOpenURLWithParams:@{@"url":url}];
        }
        return YES;
    }
    return [[SEGUhomeMediator sharedInstance] seg_UMSPPayHandleOpenURLWithParams:@{@"url":url,@"delegate":self}];
}
#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp*)resp
{
    NSString* strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString* strTitle;
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
        switch (resp.errCode) {
            case WXSuccess:
                [self shareSuccess];
                break;
            default:
                SEGLog(@"微信分享失败错误，retcode = %d, retstr = %@", resp.errCode, resp.errStr);
                break;
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        
        switch (resp.errCode) {
            case WXSuccess:
            {
                strMsg = @"支付结果：成功！";
                SEGLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                NSNotification* notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"success"];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                break;
            }
            case WXErrCodeUserCancel:{
                NSNotification* notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"WXErrCodeUserCancel"];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                break;
            }
                
            default:
                strMsg = @"支付失败";
                SEGLog(@"错误，retcode = %d, retstr = %@", resp.errCode, resp.errStr);
                break;
        }
    }
    if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]])
    {
        NSString *extMsg = [(WXLaunchMiniProgramResp *)resp valueForKey:@"extMsg"];
        if (!extMsg||extMsg.length == 0) {
            return ;
        }
        NSData *jsonData = [extMsg dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if(err) {
            NSLog(@"json解析失败：%@",err);
            return;
        }
        if ([dic.allKeys containsObject:@"errCode"]&&[dic.allKeys containsObject:@"errStr"]) {
            NSString *errorCode = dic[@"errCode"];
            NSString *errStr = dic[@"errStr"];
            if ([errorCode isKindOfClass:[NSString class]]&&[errStr isKindOfClass:[NSString class]]) {
                if ([errorCode isKindOfClass:[NSString class]]&&errorCode.integerValue == 0) {
                    NSNotification* notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"success"];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                }else {
                    [SEGAlertView showTmepMessageWithMessage:errStr];
                }
            }
            
        }
        
    }
    // 使用微信登录 获取用户信息
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *tempResp = (SendAuthResp*)resp;
        NSString *code = tempResp.code;
        if (code && code.length > 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kWeichatAuthSuccessNotification object:code];
        }
    }
}

- (void)shareSuccess {
    [SEGAlertView showTmepMessageWithMessage:@"分享成功"];
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SHARESUCCEED object:nil];
}

#pragma mark - ICBCPaySDKDelegate
/**
 *  调用工银e支付以后的结果回调
 *
 *  @param dic        回调的字典，参数中，ret_msg会有具体错误显示
 */
- (void) paymentEndwithResultDic:(NSDictionary*)dic{
    NSLog(@"pass the pkpaymentAuthorizationstatus to the page");
    NSLog(@"%@ dic",dic);
    NSLog(@"商户自行处理");
    NSString *result = [dic objectForKey:@"trandMsg"];
    NSString *tranCode= [dic objectForKey:@"tranCode"];
    if (tranCode.integerValue == 1) {
        NSNotification* notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"success"];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }else {
        [SEGAlertView showTmepMessageWithMessage:result];
    }
    
}
@end
